package com.easytopit.demo.spring.mvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/img/")
public class ImgUploadDownloadController {

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String imgUpload(@RequestParam("file") MultipartFile file, @RequestParam("names") String name, HttpServletRequest request, ModelMap modelMap) {
		// 设置存放的文件名以及目录
		int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
		String oriFileNameSuffix = lastIndexOf != -1 ? file.getOriginalFilename().substring(lastIndexOf): "";
		String destFileName = UUID.randomUUID() + oriFileNameSuffix;
		String destFilePath = request.getServletContext().getRealPath("/") + "/upload/";
		File destFile = new File(destFilePath, destFileName);
		if(!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
		// 转存到服务器本地目录
		try {
			file.transferTo(destFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		modelMap.put("name", destFileName);
		return "upload/result";
	}
	
	@RequestMapping(value = "/download/{name}", method = RequestMethod.GET)
	public void donwload(HttpServletRequest request, HttpServletResponse response, @PathVariable("name")String name) throws IOException{
		// 查找上传过的文件
		String fileStorePath = request.getServletContext().getRealPath("/") + "/upload/";
		File file = new File(fileStorePath, name);
		// 文件不存在
		if(!file.exists()){
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
			return ;
		}
		
		// 设置头部
		response.setContentType("application/octet-stream"); // 标识下载
		response.setContentLength((int) file.length()); // 文件长度
		response.setHeader( "Content-Disposition",
		         String.format("attachment; filename=\"%s\"", file.getName())); // 设置文件名称
		OutputStream os = response.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		try {
			fis.getChannel().transferTo(0, file.length(), Channels.newChannel(os)); // 写到浏览器
		} finally {
			fis.close();
		}
	}
}
